package com.leedcode;
/*
* 面试题 02.02. 返回倒数第 k 个节点
* */
public class LeedCode02_02 {
    public static void main(String[] args) {
        ListNode ln1 = new ListNode(1);
        ListNode ln2 = new ListNode(2);
        ListNode ln3 = new ListNode(3);
        ListNode ln4 = new ListNode(4);
        ListNode ln5 = new ListNode(5);
        ln1.next = ln2;
        ln2.next = ln3;
        ln3.next = ln4;
        ln4.next = ln5;
        ln5.next = null;
        int k = 1;
        int res = kthToLast(ln1, k);
        System.out.println(res);
    }
    /**
     * Definition for singly-linked list.
     * */
     static class ListNode {
         int val;
         ListNode next;
         ListNode(int x) { val = x; }
     }

    public static int kthToLast(ListNode head, int k) {
         ListNode temp = head;
         for(int i = 1; i < k; i++) {
             temp = temp.next;
         }
        while(true){
            if(temp.next==null){
                break;
            }
            head = head.next;
            temp = temp.next;
        }
        return head.val;
    }
}
